import Table from "@/components/Table";
import { Space, Button, Popconfirm, message, Modal, Form, Input, FormInstance, Tag, InputNumber, Radio, RadioChangeEvent } from "antd";
import '@/assets/styles/buttonStyles.css';
import '@/views/system/user/user.css';
import { DataType, ColumnsType } from "@/types/rewards";
import { useEffect, useState } from "react";
import { getCookie } from "@/utils/cookies";
import React from "react";
import { useNavigate } from "react-router-dom";
import baseUrl from '@/config';
import LoadingIndicator from '@/components/loading';

const Rewards: React.FC = () => {
  const [pageLoading, setPageLoading] = useState(true);
  const [data, setData] = useState<DataType[]>([]);
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpenAdd, setIsModalOpenAdd] = useState(false);
  const [selInfo, setSelInfo] = useState('');
  const [listNum, setListNum] = useState(0);
  // 修改信息变量集合
  const [editId, setEditId] = useState(0);
  const [editInfo, setEditInfo] = useState('');
  const [editInfo2, setEditInfo2] = useState('');
  const [editInfo3, setEditInfo3] = useState('');
  const [editInfo4, setEditInfo4] = useState('');
  const [editInfo5, setEditInfo5] = useState(0);
  // 新增信息集合
  const [addInfo, setAddInfo] = useState('');
  const [addInfo2, setAddInfo2] = useState('');
  const [addInfo3, setAddInfo3] = useState('');
  const [addInfo4, setAddInfo4] = useState('');
  const [addInfo5, setAddInfo5] = useState(0);

  const showModalEdit = (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      setEditId(record.id);
      setEditInfo(record.rewardsName);
      setEditInfo2(record.rewardsApplication);
      setEditInfo3(record.validLocation);
      setEditInfo4(record.validPeriod);
      setEditInfo5(record.rewardsValue);
      setIsModalOpen(true);
    }
  };

  const showModalAdd = () => {
    setIsModalOpenAdd(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleCancelAdd = () => {
    setIsModalOpenAdd(false);
  };

  const navigateTo = useNavigate();
  useEffect(() => {
    // 判断是否有token，检测用户是否已登录，如果未登录，给出提示，并将其跳转到登录页
    if (getCookie('token') == null) {
      message.error("尚未登录，不得访问！", 1);
      navigateTo("/login");
      return;
    }
    fetchData(); // 调用获取数据的函数
  }, []);


  const fetchData = async () => {
    try {
      const response = await fetch(baseUrl + '/back/rewards/getRewardsList', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.msg === '操作成功') {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleDelete = async (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      // 处理删除逻辑
      try {
        const response = await fetch(baseUrl + '/back/rewards/deleteRewardsById', {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
            'token': `${getCookie('token')}`
          },
          body: JSON.stringify(record)
        });

        if (response.ok) {
          // 请求成功
          const data = await response.json();
          // 处理响应数据
          if (data.code === 200) {
            message.success(data.msg, 1);
            fetchData();
          }
          else {
            message.warning(data.msg,);
          }
        } else {
          // 请求失败
          console.error('Error:', response.status);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  };

  // 定义按钮点击事件处理函数
  const handleModify = async () => {
    // 处理修改逻辑
    if (editInfo5 < 0) {
      message.warning('积分数不得为负数！', 1);
      return;
    }
    try {
      const response = await fetch(baseUrl + '/back/rewards/editRewardsById', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
        body: JSON.stringify({
          id: editId,
          rewardsName: editInfo,
          rewardsApplication: editInfo2,
          validLocation: editInfo3,
          validPeriod: editInfo4,
          rewardsValue: editInfo5,
          createTime: null,
          updataTime: null,
          isDeletd: 0
        })
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          message.success(data.msg, 1);
          fetchData();
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
    setIsModalOpen(false);
  };

  const handleAddInfo = async () => {
    if (addInfo5 < 0) {
      message.warning('积分数不得为负数！', 1);
      return;
    }
    // 处理新增信息逻辑
    try {
      const response = await fetch(baseUrl + '/back/rewards/addRewards', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
        body: JSON.stringify({
          id: null,
          rewardsName: addInfo,
          rewardsApplication: addInfo2,
          validLocation: addInfo3,
          validPeriod: addInfo4,
          rewardsValue: addInfo5,
          createTime: null,
          updataTime: null,
          isDeletd: 0
        })
      });

      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          message.success(data.msg, 1);
          fetchData();
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
    setIsModalOpenAdd(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "奖券名称",
      dataIndex: "rewardsName",
      key: "rewardsName",
    },
    {
      title: "价值积分",
      dataIndex: "rewardsValue",
      key: "rewardsValue",
    },
    {
      title: "用途",
      dataIndex: "rewardsApplication",
      key: "rewardsApplication",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === 'riding') {
          return <Tag color="blue">骑行</Tag>;
        } else if (text === 'driving') {
          return <Tag color="green">驾车</Tag>;
        } else if (text === 'flying') {
          return <Tag color="yellow">空乘</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag>全能卡</Tag>;
        }
      }
    },
    {
      title: "有效地区",
      dataIndex: "validLocation",
      key: "validLocation",
    },
    {
      title: "单次有效时限",
      dataIndex: "validPeriod",
      key: "validPeriod",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="default" onClick={(e) => showModalEdit(record, e)} className="edit-button">
            修改
          </Button>
          <Popconfirm
            title="提示"
            description="确定要删除吗？"
            okText="Yes"
            cancelText="No"
            onConfirm={(e) => handleDelete(record, e)}
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      className: 'hiddenColumn'
    }
  ];

  const selInfoDetail = async () => {
    try {
      setPageLoading(true);
      const response = await fetch(baseUrl + '/back/rewards/getRewardsLikeName?rewardsName=' + selInfo, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        }
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
          message.success(data.msg, 1);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const SubmitButton = ({ form }: { form: FormInstance }) => {
    const [submittable, setSubmittable] = React.useState(false);

    // Watch all values
    const values = Form.useWatch([], form);

    React.useEffect(() => {
      form.validateFields({ validateOnly: true }).then(
        () => {
          setSubmittable(true);
        },
        () => {
          setSubmittable(false);
        },
      );
    }, [values]);

    return (
      <Button type="primary" htmlType="submit" disabled={!submittable} onClick={selInfoDetail}>
        查询
      </Button>
    );
  };

  const handleSelInfoChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    setSelInfo(event.target.value);
  };

  const handleEditInfoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEditInfo(event.target.value);
  };

  const handleEditInfo2Change = (e: RadioChangeEvent) => {
    setEditInfo2(e.target.value);
  };

  const handleEditInfo3Change = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEditInfo3(event.target.value);
  };

  const handleEditInfo4Change = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEditInfo4(event.target.value);
  };

  const handleEditInfo5Change = (value: number | null) => {
    setEditInfo5(value ?? 0);
  };

  const handleAddInfoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAddInfo(event.target.value);
  };

  const handleAddInfo2Change = (e: RadioChangeEvent) => {
    setAddInfo2(e.target.value);
  };

  const handleAddInfo3Change = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAddInfo3(event.target.value);
  };

  const handleAddInfo4Change = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAddInfo4(event.target.value);
  };

  const handleAddInfo5Change = (value: number | null) => {
    setAddInfo5(value ?? 0);
  };



  return (
    <>
      <LoadingIndicator loading={pageLoading} />
      <Form form={form} name="validateOnly" layout="inline" autoComplete="off">
        <Form.Item>
          <Button type="primary" className="add-button" onClick={showModalAdd}>
            新增
          </Button>
        </Form.Item>
        <Modal title="新增奖券信息" open={isModalOpenAdd} okText="确定"
          cancelText="取消" onOk={handleAddInfo} onCancel={handleCancelAdd}>
          <Form>
            <Form.Item
              label="奖券名称"
              name="11"
              rules={[{ required: true, message: "该字段不可为空！" }]}
            >
              <Input size="large" style={{ width: '350px' }} value={addInfo} onChange={handleAddInfoChange} placeholder="（不可为空）" />
            </Form.Item>
            <Form.Item
              label="价值积分"
              name="55"
              rules={[{ required: true, message: "请填写正确积分数！", type: 'number' }]}
            >
              <InputNumber size="large" style={{ width: '350px' }} value={addInfo5} onChange={handleAddInfo5Change} placeholder="默认为0" />
            </Form.Item>
            <Form.Item
              label="用途"
              name="22"
              rules={[{ required: true, message: "该字段不可为空！" }]}
            >
              <Radio.Group defaultValue="all" size="small" style={{ width: '350px' }} value={addInfo2} onChange={handleAddInfo2Change}>
                <Radio.Button value="riding">骑行</Radio.Button>
                <Radio.Button value="driving">驾车</Radio.Button>
                <Radio.Button value="flying">空乘</Radio.Button>
                <Radio.Button value="all">全能卡</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="有效地区"
              name="33"
              rules={[{ required: true, message: "该字段不可为空！" }]}
            >
              <Input size="large" style={{ width: '350px' }} value={addInfo3} onChange={handleAddInfo3Change} placeholder="（不可为空）" />
            </Form.Item>
            <Form.Item
              label="单次有效时限"
              name="44"
              rules={[{ required: true, message: "该字段不可为空！" }]}
            >
              <Input size="large" style={{ width: '350px' }} value={addInfo4} onChange={handleAddInfo4Change} placeholder="(格式:xx分钟,且xx为正整数)" />
            </Form.Item>
          </Form>
        </Modal>
        <Form.Item name="name" label="" rules={[{ required: true, message: "查找字段内容不得为空,如不想查找请点击重置!" }]}>
          <Input placeholder="(按奖券名模糊查询）" value={selInfo} onChange={handleSelInfoChange} />
        </Form.Item>
        <Form.Item>
          <Space>
            <SubmitButton form={form} />
            <Button htmlType="reset">重置</Button>
          </Space>
        </Form.Item>
        <Tag bordered={true} color="green" className="total-tag">
          共{listNum}条记录
        </Tag>
        <Button type="link" onClick={fetchData}>查询所有</Button>
      </Form>
      <Modal title="请输入要修改的信息（不可全部为空）" open={isModalOpen} okText="确定"
        cancelText="取消" onOk={handleModify} onCancel={handleCancel}>
        <Form>
          <Form.Item
            label="奖券名称"
            name="1"
            rules={[{ required: true, message: "该字段不可为空！" }]}
          >
            <Input size="large" style={{ width: '350px' }} value={editInfo} onChange={handleEditInfoChange} placeholder="（不可为空）" />
          </Form.Item>
          <Form.Item
            label="价值积分"
            name="5"
            rules={[{ required: true, message: "请填写正确积分数！", type: 'number' }]}
          >
            <InputNumber size="large" style={{ width: '350px' }} value={editInfo5} onChange={handleEditInfo5Change} placeholder="默认为0" />
          </Form.Item>
          <Form.Item
            label="用途"
            name="2"
            rules={[{ required: true, message: "该字段不可为空！" }]}
          >
            <Radio.Group defaultValue="all" size="small" style={{ width: '350px' }} value={editInfo2} onChange={handleEditInfo2Change}>
              <Radio.Button value="riding">骑行</Radio.Button>
              <Radio.Button value="driving">驾车</Radio.Button>
              <Radio.Button value="flying">空乘</Radio.Button>
              <Radio.Button value="all">全能卡</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="有效地区"
            name="3"
            rules={[{ required: true, message: "该字段不可为空！" }]}
          >
            <Input size="large" style={{ width: '350px' }} value={editInfo3} onChange={handleEditInfo3Change} placeholder="（不可为空）" />
          </Form.Item>
          <Form.Item
            label="单次有效时限"
            name="4"
            rules={[{ required: true, message: "该字段不可为空！" }]}
          >
            <Input size="large" style={{ width: '350px' }} value={editInfo4} onChange={handleEditInfo4Change} placeholder="(格式:xx分钟,且xx为正整数)" />
          </Form.Item>
        </Form>
      </Modal>
      <Table<DataType> columns={columns} dataSource={data} />
    </>
  );
};

export default Rewards;

